<template>
  <div class="buyRexLayer">
    <p class="caption center">{{ $t('rex.redeemStakedResources') }}</p>
    <!-- 方向 -->
    <div class="item" :style="
      $store.state.app.language === 'en' ? 'padding-left: 76px;' :
      $store.state.app.language === 'ko' ? 'padding-left: 100px;' : ''">
      <span class="label" style="margin-right: 15px;">{{ $t('rex.stakedAccount') }}</span>
      <el-select v-model="receiver" class="selectWidth"
      @change="handleChangeReceiver"
      size="small"
      style="width: 160px;margin-right:13px;">
        <el-option style="font-size: 12px;"
          v-for="item in receiverList"
          :key="item.to"
          :label="item.to"
          :value="item.to">
        </el-option>
      </el-select>
      <span class="tip"
        :style="
          $store.state.app.language === 'en' ? 'margin-left: 124px;' :
          $store.state.app.language === 'ko' ? 'margin-left: 100px;' : ''">{{ $t('rex.chooseDifStake') }}</span>
    </div>
    <div class="buyRexList">
      <label>CPU:</label>
      <el-input
        type="number"
        v-model="cpuNum"
        class="inputBuyRex"
        clearable
        @mousewheel.native.prevent>
        <span slot="suffix">EOS</span>
      </el-input>
      <span class="rexStaked">{{ $t('rex.staked') }}{{cpuWeight}}</span>
    </div>
    <div class="buyRexList">
      <label>NET:</label>
      <el-input
        type="number"
        v-model="netNum"
        class="inputBuyRex"
        clearable
        @mousewheel.native.prevent>
        <span slot="suffix">EOS</span>
      </el-input>
      <span class="rexStaked">{{ $t('rex.staked') }}{{netWeight}}</span>
    </div>
    <div class="btn flexc">
      <span @click="handleStaketAction" v-loading="loading">{{ $t('rex.redeemAndBuyRex') }}</span>
    </div>
    <p class="center">{{ $t('rex.keepSomeResources') }}</p>
  </div>
</template>

<script>
import { EosModel } from '@/utils/eos';
import { toFixed } from '@/utils/validate';

export default {
  name: 'buyRexLayer', // 资源买入rex
  data() {
    return {
      symbolScience: 'EOS', // 交易环境
      loading: false,
      netNum: 0,
      cpuNum: 0,
      cpuWeight: '0.0000',
      netWeight: '0.0000',
      receiver: '',
      receiverList: []
    }
  },
  components: {},
  props: {
    buyRexBoxVisible: Boolean
  },
  watch: {
    buyRexBoxVisible: function change(val) {
      if (val) {
        this.handleExchangeScience();
        this.handleGetTableRowsForStaket();
      }
    },
  },
  computed: {},
  created() {},
  mounted() {
    this.handleExchangeScience();
    this.handleGetTableRowsForStaket();
  },
  beforeDestroy() {},
  methods: {
    // 赎回并买入REX
    handleStaketAction() {
      const cpuWeight = parseFloat(this.cpuWeight, 0);
      const netWeight = parseFloat(this.netWeight, 0);
      if (this.cpuNum > cpuWeight) {
        this.$message.error(this.$t('rex.exceedStakedNum', { type: 'CPU' }));
        return;
      }
      if (this.netNum > netWeight) {
        this.$message.error(this.$t('rex.exceedStakedNum', { type: 'NET' }));
        return;
      }
      if (!this.netNum && !this.cpuNum) {
        this.$message.error(this.$t('rex.redeemOneResource'));
        return;
      }
      this.loading = true;
      const rexProxy = localStorage.getItem('rexProxy') || 'newdex.bp';
      const params = {
        proxy: rexProxy, // 投票的节点名称
        receiver: this.receiver, // 其它用户给你的抵押
        fromCpu: `${toFixed(this.cpuNum, 4)} ${this.symbolScience}`,
        fromNet: `${toFixed(this.netNum, 4)} ${this.symbolScience}`,
      }
      const stakeCount = this.cpuNum + this.netNum;
      this.handleGetProxy({ stakeCount }).then((proxyResponse) => {
        params.proxy = proxyResponse;
        EosModel.rexUnstaketorexTransaction(params, (res) => {
          this.loading = false;
          if (res && res.broadcast) {
            // 关闭弹窗
            this.$message.success(this.$t('rex.redeemedAndBought'));
            this.$emit('listenBuyRexBoxVisible');
            return;
          }
          EosModel.handleScatterErrorBack(res);
        })
      });
    },
    // 获取投票代理账号
    async handleGetProxy(params) {
      let back = localStorage.getItem('rexProxy') || 'newdexproxy1';
      back = await this.$http.post('/pool/getProxy', params).then((res) => {
        if (res.code !== 0) {
          // const msg = res.msg || 'System error'
          // this.$message.error(msg);
          return 'newdexproxy1';
        }
        return res.proxy
      });
      return back
    },
    // 获取抵押账户
    handleGetTableRowsForStaket() {
      EosModel.getTableRowsForStaket((res) => {
        this.receiverList = res.rows;
        if (this.receiverList && this.receiverList.length === 0) {
          this.$message.warning('No resource!');
          // 关闭弹窗
          this.$emit('listenBuyRexBoxVisible');
          return;
        }
        const accountName = this.$store.state.app.scatter.identity.accounts[0].name;
        const receiver = this.receiverList.find(v => v.to === accountName);
        if (receiver) {
          this.receiver = accountName;
        } else {
          this.receiver = this.receiverList[0].to;
        }
        this.handleChangeReceiver()
      })
    },
    // 选择抵押账户
    handleChangeReceiver() {
      const to = this.receiver;
      const val = this.receiverList.find(v => v.to === to);
      if (val) {
        this.cpuWeight = val.cpu_weight;
        this.netWeight = val.net_weight;
      }
    },
    // 交易环境
    handleExchangeScience() {
      const env = process.env.NODE_ENV;
      let Science = 'EOS';
      switch (env) {
        case 'development':
          Science = 'SYS'
          break;
        case 'production':
          Science = 'EOS';
          break;
        default:
          Science = 'EOS';
          break;
      }
      this.symbolScience = Science;
    },
  },
}
</script>
<style lang="scss" scoped>
.buyRexLayer{
  .btn {
    span {
      display: inline-block;
      color: #278eda;
      border: 1px solid #278eda;
      padding: 8px 50px;
      margin: 30px auto 15px;
      cursor: pointer;
    }
  }

  .caption {
    margin-bottom: 30px;
  }

  label {
    display: inline-block;
    width: 50px;
  }

  .item {
    padding-left: 120px;
    margin-bottom: 10px;

    .tip {
      font-size: 12px;
      color: #999;
      margin-top: 6px;
      display: block;
      margin-left: 82px;
    }
  }

  .buyRexList {
    margin-bottom: 10px;
    padding-left: 145px;

    .inputBuyRex {
      width: 160px;
      line-height: 32px;
      margin-right: 10px;

      /deep/ .el-input__inner {
        padding-left: 5px;
        width: 160px;
        height: 32px;
        line-height: 32px;
        -moz-appearance: textfield;
        &::-webkit-outer-spin-button,
        &::-webkit-inner-spin-button {
          -webkit-appearance: none;
        }
      }
    }

    .rexStaked {
      margin-top: 6px;
      display: block;
      margin-left: 55px;
    }
  }
}
</style>

